<?php

namespace app\admin\controller\yxerp;

use app\admin\library\YxerpAuth;
use app\common\controller\Backend;
use think\facade\Db;
use think\facade\Validate;
use app\admin\model\yxerp\Permission as PermissionModel;
use app\admin\model\yxerp\PermissionGroup as PermissionGroupModel;

/**
 * 权限管理
 */
class Permission extends Backend
{
    /**
     * 不需要验证登录的方法
     * @var array
     */
    protected $noNeedLogin = [];

    /**
     * 不需要鉴权的方法
     * @var array
     */
    protected $noNeedPermission = [];

    /**
     * 模型对象
     * @var object
     */
    protected $model = null;
    
    /**
     * YXERP权限服务
     * @var YxerpAuth
     */
    protected $yxerpAuth = null;

    /**
     * 初始化
     */
    protected function initialize()
    {
        parent::initialize();
        $this->model = new PermissionModel();
        $this->yxerpAuth = new YxerpAuth();
    }

    /**
     * 查看权限列表
     */
    public function index()
    {
        $filter = $this->request->get('filter', '');
        $filter = (array)json_decode($filter, true);
        $page = $this->request->get('page/d', 1);
        $limit = $this->request->get('limit/d', 10);
        
        // 构建查询条件
        $where = [];
        
        // 按名称筛选
        if (isset($filter['name']) && $filter['name'] !== '') {
            $where[] = ['name', 'like', '%' . $filter['name'] . '%'];
        }
        
        // 按状态筛选
        if (isset($filter['status']) && $filter['status'] !== '') {
            $where[] = ['status', '=', $filter['status']];
        }
        
        // 按分组筛选
        if (isset($filter['group_id']) && $filter['group_id'] !== '') {
            $where[] = ['group_id', '=', $filter['group_id']];
        }
        
        // 查询列表
        $list = $this->model->where($where)
            ->with(['group'])
            ->page($page, $limit)
            ->order('id', 'desc')
            ->select();
            
        $total = $this->model->where($where)->count();
        
        // 获取所有权限组
        $groups = PermissionGroupModel::where('status', 1)->select();
        
        return $this->success('获取成功', [
            'list' => $list, 
            'total' => $total,
            'groups' => $groups
        ]);
    }

    /**
     * 添加权限
     */
    public function add()
    {
        $row = $this->request->post('row/a');
        
        // 数据验证
        $validate = Validate::rule([
            'name' => 'require|max:50',
            'code' => 'require|max:50',
            'group_id' => 'require|number',
            'description' => 'max:255',
            'status' => 'require|in:0,1',
            'data_scope' => 'in:all,dept,position,self',
        ]);
        
        $result = $validate->check($row);
        if (true !== $result) {
            return $this->error($validate->getError());
        }
        
        // 检查权限编码是否重复
        if ($this->model->where('code', $row['code'])->find()) {
            return $this->error('权限编码已存在');
        }
        
        // 添加权限
        $this->model->save($row);
        
        return $this->success('添加成功');
    }

    /**
     * 编辑权限
     */
    public function edit()
    {
        $row = $this->request->post('row/a');
        $ids = $this->request->param('ids');
        
        if (!$ids) {
            return $this->error('参数错误');
        }
        
        // 数据验证
        $validate = Validate::rule([
            'name' => 'require|max:50',
            'code' => 'require|max:50',
            'group_id' => 'require|number',
            'description' => 'max:255',
            'status' => 'require|in:0,1',
            'data_scope' => 'in:all,dept,position,self',
        ]);
        
        $result = $validate->check($row);
        if (true !== $result) {
            return $this->error($validate->getError());
        }
        
        // 检查权限编码是否重复
        $exists = $this->model->where('code', $row['code'])
            ->where('id', '<>', $ids)
            ->find();
        if ($exists) {
            return $this->error('权限编码已存在');
        }
        
        // 更新权限
        $this->model->where('id', $ids)->update($row);
        
        return $this->success('编辑成功');
    }

    /**
     * 删除权限
     */
    public function del()
    {
        $ids = $this->request->param('ids');
        
        if (!$ids) {
            return $this->error('参数错误');
        }
        
        // 检查权限是否被使用
        $employeePermissionCount = Db::name('yxerp_employee_permission')
            ->where('permission_id', 'in', $ids)
            ->count();
        
        $positionPermissionCount = Db::name('yxerp_position_permission')
            ->where('permission_id', 'in', $ids)
            ->count();
            
        $departmentPermissionCount = Db::name('yxerp_department_permission')
            ->where('permission_id', 'in', $ids)
            ->count();
            
        $adminPermissionCount = Db::name('yxerp_admin_permission')
            ->where('permission_id', 'in', $ids)
            ->count();
            
        if ($employeePermissionCount > 0 || $positionPermissionCount > 0 || 
            $departmentPermissionCount > 0 || $adminPermissionCount > 0) {
            return $this->error('该权限已被分配，无法删除');
        }
        
        // 删除权限
        $this->model->where('id', 'in', $ids)->delete();
        
        return $this->success('删除成功');
    }
    
    /**
     * 获取部门权限
     */
    public function getDepartmentPermissions()
    {
        $departmentId = $this->request->param('department_id/d', 0);
        
        if (!$departmentId) {
            return $this->error('部门ID不能为空');
        }
        
        // 获取部门已有权限
        $permissionIds = Db::name('yxerp_department_permission')
            ->where('department_id', $departmentId)
            ->column('permission_id');
            
        // 获取所有权限
        $permissions = $this->model->where('status', 1)
            ->with(['group'])
            ->select()
            ->toArray();
            
        // 整理权限数据
        $result = [];
        $groups = [];
        
        foreach ($permissions as $permission) {
            $permission['checked'] = in_array($permission['id'], $permissionIds);
            $groupId = $permission['group_id'];
            
            if (!isset($groups[$groupId])) {
                $groups[$groupId] = [
                    'id' => $groupId,
                    'name' => $permission['group']['name'] ?? '未分组',
                    'permissions' => []
                ];
            }
            
            $groups[$groupId]['permissions'][] = $permission;
        }
        
        $result = array_values($groups);
        
        return $this->success('获取成功', $result);
    }
    
    /**
     * 获取岗位权限
     */
    public function getPositionPermissions()
    {
        $positionId = $this->request->param('position_id/d', 0);
        
        if (!$positionId) {
            return $this->error('岗位ID不能为空');
        }
        
        // 获取岗位已有权限
        $permissionIds = Db::name('yxerp_position_permission')
            ->where('position_id', $positionId)
            ->column('permission_id');
            
        // 获取所有权限
        $permissions = $this->model->where('status', 1)
            ->with(['group'])
            ->select()
            ->toArray();
            
        // 整理权限数据
        $result = [];
        $groups = [];
        
        foreach ($permissions as $permission) {
            $permission['checked'] = in_array($permission['id'], $permissionIds);
            $groupId = $permission['group_id'];
            
            if (!isset($groups[$groupId])) {
                $groups[$groupId] = [
                    'id' => $groupId,
                    'name' => $permission['group']['name'] ?? '未分组',
                    'permissions' => []
                ];
            }
            
            $groups[$groupId]['permissions'][] = $permission;
        }
        
        $result = array_values($groups);
        
        return $this->success('获取成功', $result);
    }
    
    /**
     * 获取员工权限
     */
    public function getEmployeePermissions()
    {
        $employeeId = $this->request->param('employee_id/d', 0);
        
        if (!$employeeId) {
            return $this->error('员工ID不能为空');
        }
        
        // 获取员工已有权限
        $permissionIds = Db::name('yxerp_employee_permission')
            ->where('employee_id', $employeeId)
            ->column('permission_id');
            
        // 获取所有权限
        $permissions = $this->model->where('status', 1)
            ->with(['group'])
            ->select()
            ->toArray();
            
        // 整理权限数据
        $result = [];
        $groups = [];
        
        foreach ($permissions as $permission) {
            $permission['checked'] = in_array($permission['id'], $permissionIds);
            $groupId = $permission['group_id'];
            
            if (!isset($groups[$groupId])) {
                $groups[$groupId] = [
                    'id' => $groupId,
                    'name' => $permission['group']['name'] ?? '未分组',
                    'permissions' => []
                ];
            }
            
            $groups[$groupId]['permissions'][] = $permission;
        }
        
        $result = array_values($groups);
        
        return $this->success('获取成功', $result);
    }
    
    /**
     * 获取管理员权限
     */
    public function getAdminPermissions()
    {
        $adminId = $this->request->param('admin_id/d', 0);
        
        if (!$adminId) {
            return $this->error('管理员ID不能为空');
        }
        
        // 获取管理员已有权限
        $permissionIds = Db::name('yxerp_admin_permission')
            ->where('admin_id', $adminId)
            ->column('permission_id');
            
        // 获取所有权限
        $permissions = $this->model->where('status', 1)
            ->with(['group'])
            ->select()
            ->toArray();
            
        // 整理权限数据
        $result = [];
        $groups = [];
        
        foreach ($permissions as $permission) {
            $permission['checked'] = in_array($permission['id'], $permissionIds);
            $groupId = $permission['group_id'];
            
            if (!isset($groups[$groupId])) {
                $groups[$groupId] = [
                    'id' => $groupId,
                    'name' => $permission['group']['name'] ?? '未分组',
                    'permissions' => []
                ];
            }
            
            $groups[$groupId]['permissions'][] = $permission;
        }
        
        $result = array_values($groups);
        
        return $this->success('获取成功', $result);
    }
    
    /**
     * 分配权限给部门
     */
    public function assignToDepartment()
    {
        $departmentId = $this->request->post('department_id/d', 0);
        $permissionIds = $this->request->post('permission_ids/a', []);
        $dataScope = $this->request->post('data_scope', PermissionModel::DATA_SCOPE_ALL);
        
        if (!$departmentId) {
            return $this->error('部门ID不能为空');
        }
        
        // 检查部门是否存在
        $department = Db::name('yxerp_department')->where('id', $departmentId)->find();
        if (!$department) {
            return $this->error('部门不存在');
        }
        
        // 开始事务
        Db::startTrans();
        try {
            // 删除旧的权限关联
            Db::name('yxerp_department_permission')->where('department_id', $departmentId)->delete();
            
            // 添加新的权限关联
            if (!empty($permissionIds)) {
                $data = [];
                foreach ($permissionIds as $permissionId) {
                    $data[] = [
                        'department_id' => $departmentId,
                        'permission_id' => $permissionId,
                        'data_scope' => $dataScope,
                        'create_time' => time(),
                        'update_time' => time(),
                    ];
                }
                Db::name('yxerp_department_permission')->insertAll($data);
            }
            
            Db::commit();
            return $this->success('分配成功');
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error('分配失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 分配权限给岗位
     */
    public function assignToPosition()
    {
        $positionId = $this->request->post('position_id/d', 0);
        $permissionIds = $this->request->post('permission_ids/a', []);
        $dataScope = $this->request->post('data_scope', PermissionModel::DATA_SCOPE_ALL);
        
        if (!$positionId) {
            return $this->error('岗位ID不能为空');
        }
        
        // 检查岗位是否存在
        $position = Db::name('yxerp_position')->where('id', $positionId)->find();
        if (!$position) {
            return $this->error('岗位不存在');
        }
        
        // 开始事务
        Db::startTrans();
        try {
            // 删除旧的权限关联
            Db::name('yxerp_position_permission')->where('position_id', $positionId)->delete();
            
            // 添加新的权限关联
            if (!empty($permissionIds)) {
                $data = [];
                foreach ($permissionIds as $permissionId) {
                    $data[] = [
                        'position_id' => $positionId,
                        'permission_id' => $permissionId,
                        'data_scope' => $dataScope,
                        'create_time' => time(),
                        'update_time' => time(),
                    ];
                }
                Db::name('yxerp_position_permission')->insertAll($data);
            }
            
            Db::commit();
            return $this->success('分配成功');
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error('分配失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 分配权限给员工
     */
    public function assignToEmployee()
    {
        $employeeId = $this->request->post('employee_id/d', 0);
        $permissionIds = $this->request->post('permission_ids/a', []);
        $dataScope = $this->request->post('data_scope', PermissionModel::DATA_SCOPE_ALL);
        
        if (!$employeeId) {
            return $this->error('员工ID不能为空');
        }
        
        // 检查员工是否存在
        $employee = Db::name('yxerp_employee')->where('id', $employeeId)->find();
        if (!$employee) {
            return $this->error('员工不存在');
        }
        
        // 开始事务
        Db::startTrans();
        try {
            // 删除旧的权限关联
            Db::name('yxerp_employee_permission')->where('employee_id', $employeeId)->delete();
            
            // 添加新的权限关联
            if (!empty($permissionIds)) {
                $data = [];
                foreach ($permissionIds as $permissionId) {
                    $data[] = [
                        'employee_id' => $employeeId,
                        'permission_id' => $permissionId,
                        'data_scope' => $dataScope,
                        'create_time' => time(),
                        'update_time' => time(),
                    ];
                }
                Db::name('yxerp_employee_permission')->insertAll($data);
            }
            
            Db::commit();
            return $this->success('分配成功');
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error('分配失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 分配权限给管理员
     */
    public function assignToAdmin()
    {
        $adminId = $this->request->post('admin_id/d', 0);
        $permissionIds = $this->request->post('permission_ids/a', []);
        $dataScope = $this->request->post('data_scope', PermissionModel::DATA_SCOPE_ALL);
        
        if (!$adminId) {
            return $this->error('管理员ID不能为空');
        }
        
        // 检查管理员是否存在
        $admin = Db::name('admin')->where('id', $adminId)->find();
        if (!$admin) {
            return $this->error('管理员不存在');
        }
        
        // 开始事务
        Db::startTrans();
        try {
            // 删除旧的权限关联
            Db::name('yxerp_admin_permission')->where('admin_id', $adminId)->delete();
            
            // 添加新的权限关联
            if (!empty($permissionIds)) {
                $data = [];
                foreach ($permissionIds as $permissionId) {
                    $data[] = [
                        'admin_id' => $adminId,
                        'permission_id' => $permissionId,
                        'data_scope' => $dataScope,
                        'create_time' => time(),
                        'update_time' => time(),
                    ];
                }
                Db::name('yxerp_admin_permission')->insertAll($data);
            }
            
            Db::commit();
            return $this->success('分配成功');
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error('分配失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 检查当前用户是否有权限
     */
    public function checkPermission()
    {
        $permissionCode = $this->request->param('code', '');
        
        if (!$permissionCode) {
            return $this->error('权限代码不能为空');
        }
        
        $hasPermission = $this->yxerpAuth->check($permissionCode);
        
        if ($hasPermission) {
            return $this->success('有权限');
        } else {
            return $this->error('无权限');
        }
    }
    
    /**
     * 获取数据权限范围
     */
    public function getDataScope()
    {
        $permissionCode = $this->request->param('code', '');
        
        if (!$permissionCode) {
            return $this->error('权限代码不能为空');
        }
        
        $dataScope = $this->yxerpAuth->checkDataScope($permissionCode);
        
        return $this->success('获取成功', ['data_scope' => $dataScope]);
    }

    /**
 * 获取YXERP插件的系统权限规则
 */
public function getRules()
{
    // 获取原系统权限规则
    $ruleModel = new \app\admin\model\AuthRule();
    $rules = $ruleModel->where('name', 'like', 'yxerp/%')
        ->field('id,pid,name,title,ismenu,status')
        ->order('weigh', 'desc')
        ->select();
    
    // 转为树形结构
    $ruleTree = $this->buildRuleTree($rules);
    
    return $this->success('获取成功', ['rules' => $ruleTree]);
}

/**
 * 构建权限规则树
 */
protected function buildRuleTree($rules, $pid = 0)
{
    $treeList = [];
    foreach ($rules as $rule) {
        if ($rule['pid'] == $pid) {
            $children = $this->buildRuleTree($rules, $rule['id']);
            if (!empty($children)) {
                $rule['children'] = $children;
            }
            $treeList[] = $rule;
        }
    }
    return $treeList;
}

/**
 * 保存用户权限设置
 */
public function saveUserPermission()
{
    $userId = $this->request->post('user_id/d', 0);
    $ruleIds = $this->request->post('rule_ids/a', []);
    $dataScope = $this->request->post('data_scope', 'self'); // 默认个人数据
    
    if (!$userId) {
        return $this->error('用户ID不能为空');
    }
    
    // 开始事务
    Db::startTrans();
    try {
        // 获取用户已有的系统权限
        $accessModel = new \app\admin\model\AuthGroupAccess();
        $groupIds = $accessModel->where('uid', $userId)->column('group_id');
        
        // 保存系统权限规则
        // ...系统权限规则保存逻辑...
        
        // 保存YXERP数据权限
        // 先获取权限ID
        $permissionIds = [];
        if (!empty($ruleIds)) {
            // 通过rule_id查找对应的yxerp_permission
            $permissionIds = $this->model->where('code', 'in', function($query) use ($ruleIds) {
                $query->name('auth_rule')->where('id', 'in', $ruleIds)->field('name');
            })->column('id');
        }
        
        // 删除旧的员工权限关联
        Db::name('yxerp_employee_permission')->where('employee_id', $userId)->delete();
        
        // 添加新的权限关联
        if (!empty($permissionIds)) {
            $data = [];
            foreach ($permissionIds as $permissionId) {
                $data[] = [
                    'employee_id' => $userId,
                    'permission_id' => $permissionId,
                    'data_scope' => $dataScope,
                    'create_time' => time(),
                    'update_time' => time(),
                ];
            }
            Db::name('yxerp_employee_permission')->insertAll($data);
        }
        
        Db::commit();
        return $this->success('保存成功');
    } catch (\Exception $e) {
        Db::rollback();
        return $this->error('保存失败: ' . $e->getMessage());
    }
}
}